package com.transcargo.action;

import com.transcargo.data.Cache;
import com.transcargo.errors.ErrorList;
import com.transcargo.db.db;
import com.transcargo.db.dbException;
import com.transcargo.users.UserNotFoundException;
import com.transcargo.users.User;
import com.transcargo.rating.Rating;
import com.transcargo.geo.GeoObjectNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.util.Iterator;
import java.sql.SQLException;

/**
 * Date: 27.04.2011
 * Time: 16:14:01
 */
public class AddFeedbackAction extends AuthAction {
    private String mark = "";
    private String feedback = "";
    private String id = "";
    private int Id = 0;

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
        id = request.getParameter("uid");
        if (id == null || id.length() == 0 || Integer.parseInt(id) == 0) throw new ServletParametersException();
        mark = request.getParameter("mark");
        if (mark == null || mark.length() == 0) throw new ServletParametersException();
        feedback = request.getParameter("feedback");
    }
    private void servletValidateValues() throws ServletValidationException, ServletParametersException {
        Id = Integer.parseInt(id);
        if (Id == User_Id) throw new ServletParametersException();
        if (!User.validateUser(Id, dbase)) throw new ServletValidationException("User ID not found");
        if (Integer.parseInt(mark) < -2 || Integer.parseInt(mark) > 2) throw new ServletValidationException("Mark not specified");
        if (feedback == null || feedback.length() == 0) throw new ServletValidationException(ErrorList.ERROR_STR_FEEDBACK_MISSING);
        if (feedback.length() > 1024) throw new ServletValidationException(ErrorList.ERROR_STR_FEEDBACK_TOO_LONG);
    }

    private void servletExecuteAction() throws ServletActionException {
        db.PreStatement pre = null;
        try {
            pre = dbase.CreateStatement("INSERT INTO feedbacks (user_id, author, date, rating, feedback) VALUES (?, ?, NOW(), ?, ?)");
            pre.Insert(Id);
            pre.Insert(User_Id);
            pre.Insert(Integer.parseInt(mark));
            pre.Insert(feedback);
            dbase.executeUpdate(pre);

            list = dbase.execute("SELECT rating FROM ratings WHERE user_id=" + Id);
            iter = list.iterator();
            float r = 0f;
            Boolean upd = false;
            if (iter.hasNext()) {
                String[] res = iter.next();
                r = Float.parseFloat(res[0]);
                upd = true;
            }
            list = dbase.execute("SELECT rating FROM feedbacks WHERE user_id=" + Id);
            iter = list.iterator();
            int i = 0;
            while (iter.hasNext()) {
                String[] res = iter.next();
                r = Rating.calculateRating(r, i, Integer.parseInt(res[0]));
            }
            if (upd) dbase.executeUpdate("UPDATE ratings SET rating=" + r + " WHERE user_id=" + Id);
            else dbase.executeUpdate("INSERT INTO ratings (user_id, rating) VALUES (" + Id + "," + r + ")"); 
        } catch (SQLException e) {
			System.out.println("SQL exception: " + e.getMessage());
			throw new ServletActionException();
		} catch (dbException e) {
			System.out.println("Db exception: " + e.getMessage());
			throw new ServletActionException();
		}
    }
    public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		try {
            servletGetValues(request);
            servletValidateValues();
            servletExecuteAction();
            sendRedirect(response, "company.jsp?id=" + Id);
	    } catch (ServletParametersException e) {
            if (e.getMessage() != null) {
                sendError(response, new Exception(e.getMessage()));
            } else {
                sendRedirect(response, "index.jsp");
            }
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletActionException e) {
            sendError(response, new Exception("" + ErrorList.ERROR_STR_GENERIC + dbase.getError()));
        }
    }
}
